<template>
  <div>
    <el-input v-model="materialId" style="display: none"></el-input>
    <el-input v-model="materialName" readonly placeholder="请选择物料" :disabled="readonly" @clear="handleClear">
      <template #append>
        <el-button class="button" @click="selectMaterial" :disabled="readonly">选择物料</el-button>
      </template>
    </el-input>
  </div>
  <!--物料选择对话框-->
  <MaterialSelectDialogComponent ref="materialSelectDialog" @afterSubmit="afterMaterialSelect" @dialogClosed="emit('finishMaterialSelect')" />
</template>

<script setup lang="ts">
import MaterialSelectDialogComponent from '@/components/mes/MaterialSelectDialogComponent.vue';
import type { Material } from '@/types/interface/mes_interface';
import { ref } from 'vue';

const emit = defineEmits(['update:modelValue', 'afterClickSelectMaterialButton', 'finishMaterialSelect']); // 定义自定义事件
interface Props {
  readonly?: boolean; //是否只读，只读的话选择框不可用。
}
const props = withDefaults(defineProps<Props>(), {
  readonly: false
});
//物料id
const materialId = defineModel<string | null>({
  required: false,
  default: null
});
//物料名称
const materialName = defineModel<string | null>('materialName', {
  required: false,
  default: null
});

//物料选择对话框
const materialSelectDialog = ref();
//点击选择物料
const selectMaterial = async () => {
  //在点击选择按钮后，先清空表单验证
  emit('afterClickSelectMaterialButton');
  //打开物料选择对话框
  await materialSelectDialog.value.openDialog();
};
//获取在物料选择框选择的物料
const afterMaterialSelect = (materials: Material[]) => {
  //将当前选择的物料赋给相应的工艺详情
  if (materials.length > 0) {
    materialId.value = materials[0].id!;
    materialName.value = materials[0].name!;
  }
};
//清空选择物料
const handleClear = () => {
  materialId.value = null;
};
</script>

<style scoped></style>
